package controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description:
 * author: 时间
 * time: 2022-01-12-17:20
 */
public class ToArray {
    public static void main(String[] args) {
        ToArray toArray = new ToArray();
        OperationFile operationFile = new OperationFile();
        Pattern pattern2 = Pattern.compile("\\((.*?)\\)");
        System.out.println(Arrays.deepToString(toArray.fileToArray(operationFile.readRegisteredFile(), "src\\model\\registered.txt", pattern2)));
    }

    /**
     * Description: 获取文件行数，用于创建数组， 供本类使用, 参数：文件目录
     * Author: 时间
     * Date: 2022/1/12 17:27
     */
    int ArraySize(String path){
        File file = new File(path);
        FileReader f = null;
        BufferedReader f1 = null;
        int count = 0;
        try {
            f = new FileReader(file);
            f1 = new BufferedReader(f);
            while (f1.readLine() != null){
                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                assert f1 != null;
                f1.close();
                f.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return count;
    }

    /**
     * Description: 将文件读取出来的内容转为二维数组, 参数：文件读取的字符串对象, 文件目录, 正则
     * Author: 时间
     * Date: 2022/1/12 17:26
     */
    public String[][] fileToArray(StringBuffer stringBuffer, String path, Pattern pattern){
        int count = ArraySize(path);
        String[][] strings = new String[count][];
        int cou = 0;
        // stringBuffer 转 String 的方法
        String str = stringBuffer.toString();

        Matcher matcher = pattern.matcher(str);
        while (matcher.find()){
            String str1 = matcher.group(0);
            String str2 = str1.substring(1, str1.length() - 1);
            String[] strArray = str2.split("-");
            strings[cou++] = strArray;
        }
        return strings;
    }
}
